<?php

ini_set("display_errors", "On");
error_reporting(E_ALL);

// 引入数据库连接文件
require_once '../../../../sql/connection.php';

$questionID = $_POST['questionID'];
$jobID = $_POST['jobID'];

// 查询语句
$querySql = "select id, create_time, update_time, question_ID, job_ID, is_delete from `job-question` where question_ID = '$questionID' and job_ID = '$jobID' and is_delete = 0";
// 连接数据库，并查询
$result = mysqli_query($GLOBALS['conn'], $querySql);

//echo $result_config;
if (mysqli_num_rows($result) > 0) {
	echo "
<script>
    alert('该题目已存在于改作业中存在，请重新选择！');
    history.go(-1);
</script>";
} else {
	$now = date('Y-m-d H:i:s', time());
	
	// 查询语句
	$querySql = "select id, create_time, update_time, question_ID, job_ID, is_delete from `job-question` where question_ID = '$questionID' and job_ID = '$jobID' and is_delete = 1";
	// 连接数据库，并查询
	$result = mysqli_query($GLOBALS['conn'], $querySql);
	if (mysqli_num_rows($result) > 0) {
		$addSql = "UPDATE  `job-question` SET is_delete = 0 where  question_ID = '$questionID' and job_ID = '$jobID' ;";
	}else {
		$addSql = "INSERT INTO `job-question`(create_time, update_time,  question_ID, job_ID, is_delete)VALUES ('$now','$now','$questionID','$jobID',0)";
	}
	
	if (mysqli_query($GLOBALS['conn'], $addSql) ) {
		// 查询作业所包含的题目（SQL语句）
		$queryQuestionSql = "select question_type, question_opt_answer, question_completion_answer from `question_info`
              		where id IN (select question_ID from `job-question` where job_ID = '$jobID' and `job-question`.is_delete = 0) and is_delete = 0";
		// 临时存储作业答案
		$jobAanswers = "本作业答案：";
		// 连接数据库，并查询
		$resultQue = mysqli_query($GLOBALS['conn'], $queryQuestionSql);
		// 题目数
		$queNum = mysqli_num_rows($resultQue);
		// 拼接答案
		while ($row = mysqli_fetch_array($resultQue)){
			if ($row['question_type'] == 1){
				$jobAanswers = $jobAanswers . $row['question_opt_answer'];
			}elseif ($row['question_type'] == 2){
				$jobAanswers = $jobAanswers . $row['question_completion_answer'];
			}elseif ($row['question_type'] == 3){
				$jobAanswers = $jobAanswers . "本题为简答题，由教师自行判断";
			}
			$jobAanswers = $jobAanswers . '；';
		}
		// 将答案存储到数据库中（SQL语句）
		$updateAnswerSql = "UPDATE  `job_info` SET job_answers = '$jobAanswers' ,question_total = '$queNum' where id = '$jobID';";
		if (mysqli_query($GLOBALS['conn'], $updateAnswerSql)){
			echo "
            <script>
                alert('添加成功！');
                window.location.href=document.referrer;
            </script>
        ";
		}
		
	} else {
		echo "
            <script>
                alert('添加失败！');
                history.back();
            </script>
        ";
	}
	
}

